import React, { useEffect, useState ,useCallback} from 'react'
import { menulistAct, roleListAct, tokenAct, userinfoAct } from '../../store/action/commonAct'
import { connect } from 'react-redux'
import    {MD5,AES, enc}    from 'crypto-js'
import './index.less'

import  {LoginApi ,userInfoApi }  from '../../apis/userApi'
import {menuListApi, roleListApi} from '../../apis/homeApi'

import   {Button,Checkbox,message} from 'antd'
import Password from 'antd/lib/input/Password'



function Login({dispatch,history}) {

     const [remember,setRemember] = useState(false),
             [id,setId]=useState(''),
            [password,setPassword] = useState('')

      //因为useEffect的依赖项为空，所以useEffect函数相当于componentDidMount的功能
        useEffect(()=>{
            let  cache = localStorage.getItem('login-info-passWord-userCode')  
            if(!!cache){
               try {
                cache =  JSON.parse( AES.decrypt(cache,'LOGIN-INFO-key').toString(enc.Utf8))
                setId(cache.id)
                setPassword(cache.password)
               } catch (e) {
                 console.log('保存的用户登录信息错误')
               }
            }
        },[])    

       const  loginEvt  = useCallback( async ()=>{
        let  obj = {
            id:id.trim(),
            password:password.trim()
        }

        if(!obj.id){
            message.warning('请填写用户编码后在提交')
            return
        }
        
        if(!obj.password){
            message.warning('请填写用户密码后在提交')
            return
        }
 
        
        obj.password =  MD5(obj.password).toString()

        let  result = await LoginApi(obj)
     
        
        //  console.log(result)
         if(result.code !== 200){

            message.error('用户登录失败')
           return
         }

         dispatch(tokenAct(result.data.token))
         
         let  user = await userInfoApi(obj.id)
            
        // console.log(user)
        if(user.code === 200){
            dispatch(userinfoAct(user.data))


            //获取用户权限
            let  role  = await  roleListApi(user.data.role)
            
                 console.log(role)
            dispatch(roleListAct(role.data))
        } 
      

        //  记住登录的用户信息(用户密码及编码)
            if(remember){
                localStorage.setItem('login-info-passWord-userCode',AES.encrypt(JSON.stringify({
                    id:id.trim(),
                    password:password.trim()
                }),'LOGIN-INFO-key').toString())
                
            }else{
                localStorage.removeItem('login-info-passWord-userCode')
            }
             
            
             

        let menu =  await  menuListApi()
    
          //console.log(menu)
          if(menu.code === 200){
            dispatch(menulistAct(menu.data))
          }

       

           history.push('/home')
       },[remember,id,password])



    return (
        <div  className='login-container'   >
            <div  className='login-box'>
              <input  placeholder='请输入用户编码' value={id} onChange={
                evt =>{
                     setId(evt.target.value)
                }
              } />
              <input  placeholder='请输入登录密码'  type="password"   value={password}  onChange={
                evt=>{
                    setPassword(evt.target.value)
                }
              } />
              <Checkbox checked={remember}    onChange={
                evt=>{
                    setRemember(evt.target.checked)
                }
              }  >是否记住密码？</Checkbox>
              <Button block type='primary' onClick={loginEvt} >登录</Button>
            </div>
        </div>
    )
}


// connect方法的高阶组件实现了dispatch注入，mapStateToProps方法实现了两个功能 -> redux中的getState()和subscribe方法
export default connect()(Login)